package com.finger.forest;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.TileCache;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.ArcGISTiledLayer;
import com.esri.arcgisruntime.location.LocationDataSource;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.GeoElement;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.IdentifyGraphicsOverlayResult;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.base.SystemConfig;
import com.finger.forest.custom.MyDialog;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.ResourceModel;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.encode.PrefsUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 资源采集详情
 */
public class CollectionResourceDetailActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    private static final String TAG = "CollectionResourceDAct";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    private MapView mMapView;

    private LocationDisplay mLocationDisplay;

    /**
     * 弹框布局
     */
    LinearLayout layoutHotContent;

    private MyDialog myDialog;

    private ResourceModel resourceModel;

    private int id = 0;

    @Override
    protected int setView() {
        return R.layout.activity_collection_resource_detail;
    }

    @Override
    protected void receiveData() {
        Intent intent = getIntent();
        int id = intent.getIntExtra("id",0);
        Map<String,Object> mapParams = new HashMap<>();
        mapParams.put("id",id);
        //查询资源详情
        presenter.queryResourceDetail(mapParams);
    }

    @Override
    protected void initializeView() {
        mMapView = findViewById(R.id.mapView);
        setupMap();

        //定位当前位置
        setupLocationDisplay(false);
    }

    @Override
    protected void loadDataFromServer() {

    }

    private void setupMap() {
        if (mMapView != null) {
            ArcGISRuntimeEnvironment.setLicense(CommonKey.LICENSE);
            mMapView.setAttributionTextVisible(false);
            Basemap.Type basemapType = Basemap.Type.IMAGERY;
            ArcGISMap map = null;
            String isOnline = PrefsUtil.getString(CollectionResourceDetailActivity.this, CommonKey.ISONLINE);
            if (isOnline.equals("1")){
                map = new ArcGISMap(basemapType, SystemConfig.latitude, SystemConfig.longitude, SystemConfig.mapLevel);
            } else {
                String filePath = getExternalFilesDir(null).getAbsolutePath()+"/offline_map.tpk";
                Log.i(TAG,"离线文件路径："+filePath);
                TileCache tileCache = new TileCache(filePath);
                ArcGISTiledLayer tiledLayer = new ArcGISTiledLayer(tileCache);
                Basemap basemap = new Basemap(tiledLayer);
                map = new ArcGISMap(basemap);
            }
            mMapView.setMap(map);
        }

        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(CollectionResourceDetailActivity.this, mMapView) {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                Log.i(TAG,e.getX()+","+e.getY());
                Log.i(TAG,"点击");
                //获取屏幕点击坐标
                android.graphics.Point mapPoint =  new android.graphics.Point((int)e.getX(),(int)e.getY());
                //将屏幕坐标 传入 identifyGraphicsOverlaysAsync （屏幕坐标，范围，包括图形和弹出窗口时为false，最大检索数）
                final ListenableFuture<List<IdentifyGraphicsOverlayResult>> listListenableFuture = this.mMapView.identifyGraphicsOverlaysAsync(mapPoint,12, false, 5);
                //this.mMapView.identifyLayerAsync(mMapView.getMap().getOperationalLayers(),mapPoint,12, false, 5);
                //添加点击事件
                listListenableFuture.addDoneListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //获取点击的范围列表
                            List<IdentifyGraphicsOverlayResult> identifyLayerResults = listListenableFuture.get();
                            //循环图层
                            for (IdentifyGraphicsOverlayResult identifyLayerResult : identifyLayerResults) {
                                //循环所点击要素
                                for (final GeoElement geoElement : identifyLayerResult.getGraphics()) {
                                    Envelope tEnvelope = geoElement.getGeometry().getExtent();
                                    Point tPoint = tEnvelope.getCenter();
                                    Log.e(TAG,"当前点击的："+tPoint);

                                    layoutHotContent = (LinearLayout) LayoutInflater.from(CollectionResourceDetailActivity.this).inflate(R.layout.dialog_content_resource, null);

                                    //设置弹框值
                                    setLayoutContent();

                                    //弹框
                                    myDialog=new MyDialog(CollectionResourceDetailActivity.this,R.style.MyDialog);
                                    myDialog.setTitle("资源信息");
                                    myDialog.setLayout(layoutHotContent);
                                    myDialog.setYesOnclickListener("详情", new MyDialog.onYesOnclickListener() {
                                        @Override
                                        public void onYesOnclick() {
                                            Intent intent = new Intent(CollectionResourceDetailActivity.this, CollectionResourceDetailInfoActivity.class);
                                            intent.putExtra("id", id);//ID
                                            startActivity(intent);
                                        }
                                    });

                                    myDialog.setNoOnclickListener("取消", new MyDialog.onNoOnclickListener() {
                                        @Override
                                        public void onNoClick() {
                                            myDialog.dismiss();
                                        }
                                    });
                                    myDialog.show();


                                }
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                });
                return super.onSingleTapUp(e);
            }
        });

    }

    private void setLayoutContent(){
        TextView longtitudeTv = layoutHotContent.findViewById(R.id.longtitude);//经度
        TextView latitudeTv = layoutHotContent.findViewById(R.id.latitude);//纬度
        TextView resourceTypeTv = layoutHotContent.findViewById(R.id.resource_type);//类型
        TextView resourceNameTv = layoutHotContent.findViewById(R.id.resource_name);//资源名称
        TextView resourceRemarkTv = layoutHotContent.findViewById(R.id.resource_remark);//备注

        longtitudeTv.setText(String.valueOf(resourceModel.getLongitude()));
        latitudeTv.setText(String.valueOf(resourceModel.getLatitude()));
        resourceTypeTv.setText(resourceModel.getResouTypeName());
        resourceNameTv.setText(resourceModel.getName());
        resourceRemarkTv.setText(resourceModel.getRemark()==null?"":resourceModel.getRemark());
    }

    @OnClick({R.id.btn_back, R.id.btn_location, R.id.btn_zoom_in , R.id.btn_zoom_out})
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) { //防止重复点击
            switch (v.getId()) {

                //返回
                case R.id.btn_back:
                    finish();
                    break;

                //定位
                case R.id.btn_location:
                    setupLocationDisplay(true);
                    break;

                //地图放大
                case R.id.btn_zoom_in:
                    mMapView.setViewpointScaleAsync(mMapView.getMapScale() * 0.5);
                    break;

                //地图缩小
                case R.id.btn_zoom_out:
                    mMapView.setViewpointScaleAsync(mMapView.getMapScale() * 2);
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {
        switch (tag) {
            case ResponseTag.QUERY_RESOURCE_DETAIL:
                resourceModel = (ResourceModel) model;
                if (resourceModel != null){
                    id = resourceModel.getId();
                    //添加资源图标
                    createPointGraphics(resourceModel);
                }
                break;

            default:
                break;
        }
    }

    /**
     * 添加资源图标
     */
    private void createPointGraphics(ResourceModel resourceModel) {
        double longitude = resourceModel.getLongitude();
        double latitude = resourceModel.getLatitude();
        Log.i(TAG,"经纬度"+longitude+";"+latitude);

        GraphicsOverlay mGraphicsOverlay = new GraphicsOverlay();
        mMapView.getGraphicsOverlays().add(mGraphicsOverlay);

        Point point2 = new Point(longitude, latitude, SpatialReferences.getWgs84());
        BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(this, R.drawable.icon_resource);
        PictureMarkerSymbol pms = new PictureMarkerSymbol(bitmapDrawable);
        Graphic pointGraphic2 = new Graphic(point2, pms);
        mGraphicsOverlay.getGraphics().add(pointGraphic2);

        //定位热点位置
        //mMapView.setViewpointCenterAsync(point2);
    }

    @Override
    public void onError(int errcode, int tag, String message) {

    }

    private void setupLocationDisplay(boolean boo) {
        mLocationDisplay = mMapView.getLocationDisplay();
        mLocationDisplay.startAsync();

        mLocationDisplay.addLocationChangedListener(new LocationDisplay.LocationChangedListener() {
            @Override
            public void onLocationChanged(LocationDisplay.LocationChangedEvent locationChangedEvent) {
                LocationDataSource.Location location=locationChangedEvent.getLocation();
                Point point=location.getPosition();
                Log.i(TAG, "定位===》"+point.toString());

                if (boo){
                    // center on tapped point
                    mMapView.setViewpointCenterAsync(point,SystemConfig.mapScale);
                }

                mLocationDisplay.removeLocationChangedListener(this);
            }
        });
    }

}
